package com.yiwei.jmx.activity;

import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.widget.ImageView;
import android.widget.TextView;

import com.yiwei.jmx.R;
import com.yiwei.jmx.adapter.CarBrandAdapter;
import com.yiwei.jmx.api.Api;
import com.yiwei.jmx.api.model.CarBrandListModel;
import com.yiwei.jmx.base.BaseActivity;
import com.yiwei.jmx.event.CarSelectEvent;
import com.yiwei.jmx.util.Network;
import com.yiwei.jmx.util.RxLifeUtil;
import com.yiwei.jmx.util.ToastUtil;
import com.yiwei.jmx.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class CarBrandListActivity extends BaseActivity {

    @BindView(R.id.txt_title)
    TextView txtTitle;

    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.list)
    RecyclerView list;

    private Unbinder unbiner;
    private CarBrandAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_car_brand_list);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
    }

    private void init() {
        txtTitle.setText("选择品牌");
        adapter = new CarBrandAdapter(this);
        adapter.setOnChooseListener(new CarBrandAdapter.OnChooseListener() {
            @Override
            public void onSuccess(CarBrandListModel.DataBean item) {
                EventBus.getDefault().post(new CarSelectEvent(item));
                finish();
            }
        });
        list.setAdapter(adapter);
        getCarBrandList();
    }

    public void getCarBrandList() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        Api.api_service.getCarBrandList().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    adapter.update(result.data);
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbiner.unbind();
        unbiner = null;
    }

    @OnClick(R.id.btn_back)
    public void onViewClicked() {
        finish();
    }
}
